const makeFile = (imgSrc): Promise<string> => {
  const file = wx.getFileSystemManager()
  const number = Math.random()
  return new Promise((resolve, reject) => {
    const filePath = wx.env.USER_DATA_PATH + '/pic' + number + '.png'
    file.writeFile({
      filePath, // 表示生成一个临时文件名
      data: imgSrc.slice(22),
      encoding: 'base64',
      success: () => {
        resolve(filePath)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

const saveFile = async (imgSrc) => {
  const filePath = await makeFile(imgSrc)
  wx.saveImageToPhotosAlbum({
    filePath
  })
    .then(() => {
      wx.showToast({
        title: '保存成功'
      })
    })
    .catch(() => {
      wx.showToast({
        title: '保存失败，请检查系统权限',
        icon: 'error'
      })
    })
}
const shareFile = async (imgSrc) => {
  const filePath = await makeFile(imgSrc)
  wx.showShareImageMenu({
    path: filePath
  })
}

export { saveFile, shareFile }
